package job.work.utils;

import org.apache.commons.lang.StringUtils;

import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度地图工具类
 *
 */
public class LatitudeUtils {
    public static final String KEY_1 = "Rmq9nxrLkl8HiDcLL6mcsSvFZPcrUmZu";

    private static final double EARTH_RADIUS = 6371393; // 地球平均半径,单位：m
    /**
     * 通过AB点经纬度获取距离
     *
     * @param lat 纬度
     * @param lng B点(经，纬)
     * @return 距离(单位：米)
     */
    public static int getDistance(double lng,double lat,double lng2,double lat2) {
        Point2D pointA = new Point2D.Double(lng,lat);
        Point2D pointB =  new Point2D.Double(lng2,lat2);
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(pointA.getX()); // A经弧度
        double radiansAY = Math.toRadians(pointA.getY()); // A纬弧度
        double radiansBX = Math.toRadians(pointB.getX()); // B经弧度
        double radiansBY = Math.toRadians(pointB.getY()); // B纬弧度

        // cosβ1cosβ2cos（α1-α2）+sinβ1sinβ2
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
        double acos = Math.acos(cos); // 反余弦值
        return (int)(EARTH_RADIUS * acos); // 最终结果
    }

    public static String getDistance(String address,double lat,double lng) throws Exception{
        Map map = LatitudeUtils.getGeocoderLatitude(address);
        return "距离您"+LatitudeUtils.getDistance(Double.valueOf(map.get("lat").toString()),Double.valueOf(map.get("lng").toString()),lat,lng)+"m";
    }
    /**
     * 返回输入地址的经纬度坐标
     * key lng(经度),lat(纬度)
     */
    public static Map<String,String> getGeocoderLatitude(String address) throws Exception{
        BufferedReader in = null;
        Map<String,String> map = null;
        try {
            //将地址转换成utf-8的16进制
            address = URLEncoder.encode(address, "UTF-8");
//       如果有代理，要设置代理，没代理可注释
//		System.setProperty("http.proxyHost","192.168.1.188");
//		System.setProperty("http.proxyPort","3128");
            URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+ KEY_1);

            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));
            String res;
            StringBuilder sb = new StringBuilder("");
            while((res = in.readLine())!=null){
                sb.append(res.trim());
            }
            String str = sb.toString();

            if(StringUtils.isNotEmpty(str)){
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){
                    String lng = str.substring(lngStart+5, lngEnd);
                    String lat = str.substring(lngEnd+7, latEnd);
                    map = new HashMap<String,String>();
                    map.put("lng", lng);
                    map.put("lat", lat);
                    return map;
                }
            }
        }catch (Exception e) {
            throw new Exception(e);

        }finally{
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static void main(String args[]){
//        Map<String, String> json = LatitudeUtils.getGeocoderLatitude("北京亮马桥");
//        System.out.println("lng : "+json.get("lng"));
//        System.out.println("lat : "+json.get("lat"));
    }

}

